//
//  PageModel.m
//  DragViewDemo
//
//  Created by 吳瀾洲 on 2020/8/18.
//  Copyright © 2020 kingboyrang. All rights reserved.
//

#import "PageModel.h"



@implementation PageModel



//获取最大的size
- (CGSize)getButtonMaxSize:(NSArray <ButtonModel*> *)buttons{
    CGFloat maxHeight = 0; //最大高度
    CGFloat maxWidth = 0; //最大宽度
    if (buttons && [buttons count]>0) {
        for (ButtonModel *model in buttons) {
            if (maxHeight<model.height) {
                maxHeight = model.height;
            }
            if (maxWidth<model.width) {
                maxWidth = model.width;
            }
        }
    }
    return CGSizeMake(maxWidth, maxHeight);
}


//布局调整
- (NSArray <NSArray <ButtonModel *> *> *)showInView:(UIView *)innerView buttons:(NSArray <ButtonModel *> *)buttons isPortrait:(BOOL)portrait{
    
    if (buttons && [buttons count]>0) {
        
        NSMutableArray  *rowData = [NSMutableArray arrayWithCapacity:0];
        //总按钮数
        NSInteger total = [buttons count];
        
        CGSize maxSize = [self getButtonMaxSize:buttons];
        
        //列数
        NSInteger col = 0;
        if (portrait) { //竖屏
            col = self.column;
        }else{
            //横屏
            col = (innerView.frame.size.width - 2*kLeftRightSpaceWidth)/ (kMiddleSpaceWidth + maxSize.width + kLeftRightPaddingSpaceWidth);
        }
        
        NSLog(@"innerView frame = %@",NSStringFromCGRect(innerView.frame));
        
        //总行数
        NSInteger row = total % col == 0?total / col : (total / col)+1;
        
        
        //最大宽度
        CGFloat maxWidth = (innerView.frame.size.width - 2*kLeftRightSpaceWidth - kMiddleSpaceWidth* (col -1))/col; //最大宽度
        //最大高度
        CGFloat maxHeight = maxSize.height;
        
        //重新计算左右间距
        CGFloat marginLeftRight = (innerView.frame.size.width - col * maxWidth - kMiddleSpaceWidth* (col -1))/2.0;
        
        NSLog(@"marginLeftRight = %f",marginLeftRight);
        for (NSInteger i=0;i<row;i++) {
            
            NSMutableArray *arr = [NSMutableArray arrayWithCapacity:0];
            for (NSInteger j=0; j<col; j++) {
                
                NSInteger index = i*col+j;
                if (index<total){
                    CGFloat x = marginLeftRight+ j * kMiddleSpaceWidth + maxWidth * j;
                    CGFloat y = (i+1) * kUpDownSpaceWidth + i*maxHeight;
                    ButtonModel *model = [buttons objectAtIndex:index];
                    model.frame = CGRectMake(x, y, maxWidth, maxHeight);
                    model.tag = KButtonItemTag + index;
                    [arr addObject:model];
                }else{
                    break;
                }
            }
            [rowData addObject:arr];
        }
        
        return rowData;
        
        
    }
    return nil;
}

@end
